if (typeof jQuery === 'undefined') {
	throw new Error('需要先加载Query！')
}

/**
 * 自定义组件，命名空间为 bootman
 * 
 * @param $
 */
+function($) {
    //	默认参数
    var defaluts = {
        remoteUrl: 'http://localhost:9000/',
        //	正确返回码
        normalCode : 0,
        //	未授权异常
        unAuthorizeCode : 1007
    };
    
	var Bootman = function(options) {
		//	初始化参数
		this.options = $.extend({}, defaluts, options);
	};

	var showMask = function(msg,maskDivClass){
		hideMask();
        // 参数
        var op = {
            opacity: 0.8,
            z: 10000,
            bgcolor: '#ccc'
        };
        
        var original=$(document.body);
        var position={top:0,left:0};
        
        // 创建一个 Mask 层，追加到对象中
        var maskDiv=$('<div class="maskdivgen">&nbsp;</div>');
        maskDiv.appendTo(original);
        var maskWidth=original.outerWidth();
        if(!maskWidth){
            maskWidth=original.width();
        }
        var maskHeight=original.outerHeight();
        if(!maskHeight){
            maskHeight=original.height();
        }
        maskDiv.css({
            position: 'absolute',
            top: position.top,
            left: position.left,
            'z-index': op.z,
          width: maskWidth,
            height:maskHeight,
            'background-color': op.bgcolor,
            opacity: 0
        });
        if(maskDivClass){
            maskDiv.addClass(maskDivClass);
        }
        if(msg){
            var msgDiv=$('<div style="position:absolute;border:#6593cf 1px solid; padding:2px;background:#ccca"><div style="line-height:24px;border:#a3bad9 1px solid;background:white;padding:2px 10px 2px 10px">'+msg+'</div></div>');
            msgDiv.appendTo(maskDiv);
            var widthspace=(maskDiv.width()-msgDiv.width());
            var heightspace=(maskDiv.height()-msgDiv.height());
            msgDiv.css({
                        cursor:'wait',
                        top:(heightspace/2-2),
                        left:(widthspace/2-2)
              });
          }
          maskDiv.fadeIn('fast', function(){
            // 淡入淡出效果
            $(this).fadeTo('slow', op.opacity);
        })
	};
	
	var hideMask = function(){
        var original=$(document.body);
        
	    original.find("> div.maskdivgen").fadeOut('slow',0,function(){
	         $(this).remove();
	    });		
	};
	
	Bootman.prototype.showMask = showMask;
	Bootman.prototype.hideMask = hideMask;
	
	Bootman.prototype.httpGet = function (url,successfn, errorfn) {
		$.ajax({ 
			url: url,
			type:'GET', 
			dataType : 'json',
			beforeSend: function(XHR) { 
				showMask('执行GetHttp中....');
			},
			complete: function(XHR, TS) {
				hideMask();
			},
			success: function(d){ 
				successfn(d);
			},
            error: function(e){
            	errorfn(e);
            }
		});
	};

	Bootman.prototype.httpPost = function(url, data, successfn, errorfn) {
		var trimData = {};
		
		if(data == null){
			trimData = data;
		}else{
			if( typeof data == "object" ){ 
				$.each(data,function(i, n){
					trimData[i] = $.trim(n);
				}); 
			}else if(typeof data == "string"){
				trimData = $.trim(data);
			}else{
				trimData = data;
			}
		}
		
		$.ajax({ 
			url: url,
			type:'POST',
			data: trimData,
			async:true,
			dataType : 'json',
			beforeSend: function(XHR) { 
				showMask('执行PostHttp中....');
			},
			complete: function(XHR, TS) {
				hideMask();
			},
			success: function(d){
				successfn(d);
			},
            error: function(e){
            	errorfn(e);
            }
		});
	};
	
    /**
     * 如果token为空则不进行URL拼接
     */
	Bootman.prototype.remoteGet = function (url, token, successfn, errorfn) {
		$.ajax({ 
			url: this.options.remoteUrl + url,
			type:'GET', 
            dataType:"JSON",
			beforeSend: function(request) { 
				//	设置认证信息
				request.setRequestHeader("Authorization", token);
				showMask();
			},
			complete: function(XHR, TS) {
				hideMask();
			},
			success: function(d){
				successfn(d);	
			},
            error: function(e){
                errorfn(e);
            }
		});
	};

	Bootman.prototype.remotePost = function(url, token, data, successfn, errorfn, errorLogin) {
		var trimData = {};
		
		if(data == null){
			trimData = data;
		}else{
			if( typeof data == "object" ){ 
				$.each(data,function(i, n){
					trimData[i] = $.trim(n);
				}); 
			}else if(typeof data == "string"){
				trimData = $.trim(data);
			}else{
				trimData = data;
			}
		}
		
		var tempUrl = url;
		if(token){
			tempUrl = tempUrl + "?token=" + token;
		}
		
		$.ajax({ 
			url: $.icfans.define.host + tempUrl,
			type:'POST',
			async:true,
			data: JSON.stringify(trimData),
		    headers: {
		    	"Content-Type": "application/json; charset=utf-8"
		    },				
			dataType : 'json',
			beforeSend: function(XHR) { 
				$.utils.showMask();
			},
			complete: function(XHR, TS) {
				$.utils.hideMask();
			},
			success: function(d){
				if(d.code == this.options.unAuthorizeCode){	//	未通过身份验证
            		$.utils.showTip("请求已过期，请重新登录。", "danger");
            		setTimeout(function () { 
            			window.location.href = $.icfans.define.login_page;
            		},3000);					
				}else if(d.code == this.options.normalCode){	//	正常返回
					successfn(d);	
				}else{
					errorLogin(d);
				}
			},
            error: function(e){
                errorfn(e);
            }
		});
	};
	
	Bootman.prototype.checkToken = function(){
		var user = JSON.parse(localStorage.getItem('token'));
	}
	
	Bootman.prototype.setToken = function(o){
		localStorage.setItem('token', JSON.stringify(o));
	}
	
	//	执行BootmanAdmin的JS插件
	$.extend({"bootMan": new Bootman(bootMan_Admin_Options)});
}(jQuery);